import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToMany,
  JoinTable,
} from 'typeorm';
import { SysPost } from '../../sys-post/entities/sys-post.entity';
import { SysRole } from '../../sys-role/entities/sys-role.entity';

@Entity('sys_user')
export class SysUser {
  @PrimaryGeneratedColumn()
  readonly user_id: number;

  @Column()
  dept_id: number | null;

  @Column({ nullable: true })
  user_name: string;

  @Column({ name: 'nick_name', nullable: true })
  // nick_name: string;
  nickName: string;
  @Column({ default: '00' })
  user_type: string;

  @Column()
  email: string;

  @Column()
  phonenumber: string;

  @Column()
  sex: string;

  @Column()
  avatar: string;

  @Column()
  password: string;

  @Column()
  status: string;

  @Column()
  del_flag: string;

  @Column()
  login_ip: string;

  @Column()
  login_date: Date | null;

  @Column()
  create_by: string;

  @Column()
  create_time: Date | null;

  @Column()
  update_by: string;

  @Column()
  update_time: Date | null;

  @Column()
  remark: string;

  @ManyToMany(() => SysPost, (post) => post.users)
  @JoinTable({
    name: 'sys_user_post',
    joinColumn: {
      name: 'user_id',
      referencedColumnName: 'user_id',
    },
    inverseJoinColumn: {
      name: 'post_id',
      referencedColumnName: 'post_id',
    },
  })
  posts: SysPost[];

  @ManyToMany(() => SysRole, (role) => role.users)
  @JoinTable({
    name: 'sys_user_role',
    joinColumn: {
      name: 'user_id',
      referencedColumnName: 'user_id',
    },
    inverseJoinColumn: {
      name: 'role_id',
      referencedColumnName: 'role_id',
    },
  })
  roles: SysRole[];

  static isAdmin(userId: number): boolean {
    return userId !== null && 1 === userId;
  }
}
